//添加任务
import React from "react";
import type { FormProps } from "antd";
import { Button, Form, Input, Radio, InputNumber, DatePicker } from "antd";
import { TaskAddType } from "@/store/interface";
import { addTaskTable } from "@/axios";

//表单内部用类型 - 附加提示字段
interface TaskFormType extends TaskAddType {
  image: string; //图片素材
  video: string; //视频素材
  msg: string; //要求等
}

//准备类型
type FieldType = TaskFormType;

//准备输入框
const { TextArea } = Input;

//准备时间段选择
const { RangePicker } = DatePicker;

//准备提交
const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
  console.log("Success:", values);

  // 将选中的日期格式化为 'YYYY年MM月DD日' 格式
  values.task_time = values.task_time.map((date: any) =>
    date.format("YYYY年MM月DD日")
  );

  //将附加信息整理为对象
  const { image, video, msg } = values;
  const newObj = { image, video, msg };
  //对象转为JSON字符串并存储
  values.source = JSON.stringify(newObj);
  console.log(values);
  //添加数据
  addData(values);
};

const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (errorInfo) => {
  console.log("Failed:", errorInfo);
};

//添加数据
const addData = async (data: TaskAddType) => {
  // 发送POST请求
  const state = await addTaskTable(data);

  //成功添加则清除输入框
  if (state) {
    alert("添加成功");
  }
};

const App: React.FC = () => (
  <Form
    name="task_add"
    labelCol={{ span: 8 }}
    wrapperCol={{ span: 16 }}
    style={{ maxWidth: 600 }}
    initialValues={{ type: "douyin" }}
    onFinish={onFinish}
    onFinishFailed={onFinishFailed}
    autoComplete="off"
  >
    <Form.Item<FieldType> label="任务标题" name="title">
      <Input />
    </Form.Item>
    <Form.Item<FieldType> label="类型" name="type">
      <Radio.Group>
        <Radio value="douyin"> 抖音 </Radio>
        <Radio value="kuaishou"> 快手 </Radio>
        <Radio value="weibo"> 微博 </Radio>
      </Radio.Group>
    </Form.Item>

    <Form.Item<FieldType> label="奖励" name="reward">
      <InputNumber addonAfter="积分" />
    </Form.Item>
    <Form.Item<FieldType> label="时间" name="task_time">
      <RangePicker />
    </Form.Item>
    <Form.Item<FieldType> label="图片链接" name="image">
      <Input />
    </Form.Item>

    <Form.Item<FieldType> label="视频链接" name="video">
      <Input />
    </Form.Item>
    <Form.Item<FieldType> label="描述" name="msg">
      <TextArea placeholder="提示内容" autoSize={{ minRows: 3, maxRows: 5 }} />
    </Form.Item>

    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
      <Button type="primary" htmlType="submit">
        添加任务
      </Button>
    </Form.Item>
  </Form>
);

export default App;
